<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted  } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { publishChapter, isDraft, getDetailChapter, updateChapter } from '@/api/book/index.js'
import { message } from 'ant-design-vue'
export default {
  components: { Editor, Toolbar },
  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    const route = useRoute()
    const router = useRouter()
    let queryInfo = ref({})
    queryInfo.value = route.query
    // 内容 HTML
    const valueHtml = ref('')
    const chapterName = ref('')
    // 直接发布 更新章节
    const loading = ref(false)
    // 存为草稿
    const draftLodaing = ref(false)
    const isBookDraft = ref(false)
    const boosStatus = ref(0)
    const editorConfig = { 
      placeholder: '请输入内容...' ,
      MENU_CONF: {
        fontSize: {
          fontSizeList: ['14px', '16px', '18px', '20px']
        }
      }  
    }
    const toolbarConfig = { toolbarKeys: ['fontSize'] }
    onMounted(() => {
      isDraft({ id: queryInfo.value.novelId })
        .then(res => isBookDraft.value = res)
      // 如果有cid则编辑
      if (queryInfo.value.cid) {
        getDetailChapter({ id: queryInfo.value.cid})
          .then(res => {
            valueHtml.value = res.chapterContentMarkdown
            chapterName.value = res.chapterName
            boosStatus.value = res.status
          })
      }
    })
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })
    const handleCreated = editor => {
      editorRef.value = editor // 保存editore实例
    }
    // 获取参数
    const getParams = status => ({
      chapterName: chapterName.value, // 章节名称
      chapterNo: queryInfo.value.chapter, // 章节数
      novelId: queryInfo.value.novelId, // 小说ID
      wordNums: editorRef.value.getText().length,
      chapterContentMarkdown: valueHtml.value,
      status
    })
    // 发布章节
    const handlePublishChapter = status => {
      loading.value = true
      publishChapter(getParams(status))
        .then(() => {
          message.success('发布成功')
          loading.value = false
          return router.push({ name: 'manage', query: { ...route.query, chapter: (+queryInfo.value.chapter) + 1 }})
        })
        .catch(err =>
          message.error( err || '发布失败')
        )
        .finally(() =>
          loading.value = false
        )
    }
    // 存为草稿
    const handlePublistDraft = status => {
      draftLodaing.value = true
      publishChapter(getParams(status))
        .then(() => {
          message.success('发布成功')
          draftLodaing.value = false
          return router.push({ name:'draft', query: { ...route.query, chapter: (+queryInfo.value.chapter) + 1 }})
        })
        .catch(err =>
          message.error( err || '发布失败')
        )
        .finally(() =>
          draftLodaing.value = false
        )
    }
    // 更新章节
    const handleUpdate = () => {
      loading.value = true
      const params = getParams(boosStatus.value)
      updateChapter({ id: route.query.cid, ...params })
        .then(() => {
          message.success('更新成功')
          loading.value = false
          delete route.query.cid
          if (boosStatus.value) {
            return router.push({ name: 'manage', query: { ...route.query, chapter: (+queryInfo.value.chapter) + 1 }})
          }
          return router.push({ name:'draft', query: { ...route.query, chapter: (+queryInfo.value.chapter) + 1 }})
        })
        .catch(err =>
          message.error( err || '更新失败')
        )
        .finally(() =>
          loading.value = false
        )
    }
    // 返回
    const handleBack = () => router.back()

    return {
      isBookDraft,
      loading,
      draftLodaing,
      chapterName,
      handleBack,
      handlePublishChapter,
      handlePublistDraft,
      handleUpdate,
      queryInfo,
      editorRef,
      valueHtml,
      mode: 'simple',
      toolbarConfig,
      editorConfig,
      handleCreated
    }
  }
}
</script>  
<template>
  <div class="header-book">
    <div class="header-book-wrapper">
      <span class="back" @click="handleBack">返回</span>
      <span>{{ queryInfo.title ? `《${queryInfo.title}》` : '' }}</span>
    </div>
    <div class="info-wrapper">
      <div class="detail-wrapper">
        <span class="chapter">第{{ queryInfo.chapter }}章</span>
        <div class="title">
          <a-input v-model:value="chapterName" class="title-input" style="width: 400px;"  max-lenght="20"  placeholder="请输入章节名称，最多20个字"></a-input>
        </div>
      </div>
      <div class="btn-wrapper" v-if="queryInfo.cid">
        <a-button type="primary"  shape="round" class="btn" :loading="loading" @click="handleUpdate">更新章节</a-button>
      </div>
      <div class="btn-wrapper" v-else>
        <a-button type="primary"  ghost shape="round" class="btn" :loading="draftLodaing" @click="() => handlePublistDraft(0)">存为草稿</a-button>
        <a-button type="primary" v-if="!isBookDraft" shape="round" :loading="loading" @click="() => handlePublishChapter(1)">立即发布</a-button>
      </div>
    </div>
  </div>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      class="content"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<style lang="less" scoped>
.content {
  min-height: calc(100vh - 344px);
  padding: 24px 40px;
}
.header-book {
  &-wrapper {
    margin-bottom: 20px;
    font-size: 16px;
    .back {
      font-weight: 700;
      color: #222;
      margin-right: 12px;
      cursor: pointer;
    }
  }
  .info-wrapper {
    display: flex;
    justify-content: space-between;
    height: 40px;
    line-height: 40px;    
    margin-bottom: 20px;
    .detail-wrapper {
      display: flex;
      width: 700px;
    }
    .chapter {
      font-size: 16px;
      margin-right: 20px;
      font-weight: 700;
    }
    .title-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
    .btn-wrapper {
      flex: 1;
      text-align: right;
      .btn {
        margin-right: 15px;
      }
    }
  }
}
</style>